package main

import (
	"database/sql"

	"flag"
	"fmt"
	"reflect"
	"strings"

	_ "github.com/mattn/go-sqlite3"
)

func main() {
	var offset = flag.Int("offset", 0, "begin index")
	var num = flag.Int("limit", 10, "Number of records to show")
	var table = flag.String("table", "", "table to show")
	flag.Parse()
	if flag.Arg(0) == "" {
		panic("需要输入数据库文件名")
	}
	db, err := sql.Open("sqlite3", "data.db")
	if err != nil {
		panic(err)
	}
	defer db.Close()
	fmt.Printf("显示参数：OFFSET=%d LIMIT=%d\n", *offset, *num)
	if *table == "" {
		rows, err := db.Query("SELECT name from sqlite_master WHERE type='table';")
		if err != nil {
			panic(err)
		}
		for {
			if rows.Next() == false {
				return
			}
			var tname string
			err = rows.Scan(&tname)
			if err != nil {
				fmt.Println(err.Error())
				break
			}
			fmt.Println(tname)
		}
		return
	}

	rows, err := db.Query(fmt.Sprintf("SELECT * FROM %s LIMIT %d OFFSET %d;", *table, *num, *offset))
	if err != nil {
		panic(err)
	}
	cnames, err := rows.Columns()
	if err != nil {
		panic(err)
	}
	fmt.Println(strings.Join(cnames, "\t"))
	ctypes, err := rows.ColumnTypes()
	if err != nil {
		panic(err)
	}
	values := []interface{}{}
	for _, t := range ctypes {
		v := reflect.New(t.ScanType())
		values = append(values, v.Interface())
	}
	for {
		if rows.Next() == false {
			break
		}

		err = rows.Scan(values...)
		if err != nil {
			fmt.Println(err.Error())
			break
		}
		line1 := ""
		for _, v := range values {
			valueFunc := reflect.ValueOf(v).MethodByName("Value")
			res := valueFunc.Call(nil)
			line1 = line1 + fmt.Sprintf("%v\t", res[0].Elem())
		}
		fmt.Println(">" + line1)
	}

}
